﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls


Imports Boogaloo.Core.BLL
Imports Boogaloo.Core.UI.ControlAdapters


Namespace UI

    Public Class BasePage
        Inherits Boogaloo.Base.UI.BasePage

        Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs)
            MyBase.OnPreInit(e)

            ' Set the siteroot 
            If Groove.site_root Is Nothing Then
                Throw New HttpException(404, "Server Name (Domain Name) not registered with Boogaloo")
            End If

            '' Get the node that is to be displayed on this render
            If Not Page.IsPostBack And Not Page.IsCallback Then

                If Request.RawUrl IsNot Nothing Then
                    If Request.RawUrl.Contains("?node=") Or Request.RawUrl.Contains("?permid") Then

                        If Groove.site_current_node IsNot Nothing Then
                            Response.Clear()
                            Response.StatusCode = 301
                            Response.AddHeader("location", Groove.site_current_node.GetVirtualPath())
                            Response.End()
                        End If

                    End If
                End If

            End If




            ' verify node belongs to this root
            If Groove.site_current_node Is Nothing OrElse Groove.site_current_node.root_id <> Groove.site_root.root_id Then
                HttpContext.Current.Response.StatusCode = HttpStatusCode.NotFound
                Response.End()
                'Throw New HttpException(404, "HTTP Error 404 - File or directory not found.")
            End If


            ' verify node can display
            If Groove.site_current_node.display = False Or Groove.site_current_node.publish_date > DateTime.Now Or Groove.site_current_node.layout Then
                If Not Context.User.IsInRole("Boogaloo Admin") Then
                    HttpContext.Current.Response.StatusCode = HttpStatusCode.NotFound
                    Response.End()
                    'Throw New HttpException(404, "HTTP Error 404 - File or directory not found.")
                End If

            End If

            ' only display webpages and local files
            If Groove.site_current_node.node_type = NodeType.ExternalUrl Then
                Response.Clear()
                If String.IsNullOrEmpty(Groove.site_current_node.external_url) Then
                    HttpContext.Current.Response.StatusCode = HttpStatusCode.NotFound
                    Response.End()
                Else
                    Response.StatusCode = 301
                    Response.AddHeader("location", Groove.site_current_node.external_url)
                End If
                Response.End()
            ElseIf Groove.site_current_node.node_type = NodeType.Folder Then
                HttpContext.Current.Response.StatusCode = HttpStatusCode.NotFound
                Response.End()
            End If

            ' configure the master page and themes
            Dim master As MasterTemplate = MasterTemplate.GetMasterTemplate(Groove.site_current_node.master_template_id)
            Me.MasterPageFile = master.master_virtual_path

            If Groove.site_current_node.theme_id > 0 Then
                Dim pageTheme As Boogaloo.Core.BLL.Theme = Boogaloo.Core.BLL.Theme.GetTheme(Groove.site_current_node.theme_id)
                Me.Theme = pageTheme.name
            End If


            ' Increment the viewcount
            If Not Context.User.IsInRole("Boogaloo Admin") Then Groove.site_current_node.IncrementViewcount()


        End Sub


        Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
            MyBase.OnLoad(e)



            ' Add the header information
            Page.Title = Groove.site_current_node.page_title

            ' Reset the form action due to the rewrite
            'Page.Form.Attributes("action") = Groove.site_current_node.GetVirtualPath & Groove.QueryString().ToString


            ' Add the any controls to the page that have been configured for this node
            Dim cphs As Dictionary(Of String, ContentPlaceHolder) = Boogaloo.Base.Reflection.ContentPlaceHolderDictionary(Me.Master)
            Dim nc As NodeControl = Nothing
            Dim node_controls As List(Of NodeControl) = Groove.site_current_node.node_controls
            For Each nc In node_controls
                If cphs.ContainsKey(nc.contentplaceholder) Then
                    Dim obj As Object = Me.LoadControl(nc.control.ascx_source)
                    Try
                        obj.node_control_id = nc.node_control_id
                    Catch ex As Exception
                        ' This object may not require node_control_id so let it slide!
                    End Try

                    Try
                        cphs(nc.contentplaceholder).Controls.Add(obj)
                    Catch ex As Exception
                        cphs(nc.contentplaceholder).Controls.Add(New LiteralControl(ex.Message))
                    End Try

                End If
            Next

            Dim cph_head As ContentPlaceHolder = Nothing
            If cphs.ContainsKey("Head") Then
                cph_head = cphs("Head")
            ElseIf cphs.ContainsKey("head") Then
                cph_head = cphs("head")
            End If


            ' Add meta information
            AddMetaTag("keywords", Groove.site_current_node.meta_keywords, cph_head)
            AddMetaTag("description", Groove.site_current_node.meta_description, cph_head)
            AddMetaTag("abstract", Groove.site_current_node.meta_abstract, cph_head)
            AddMetaTag("author", Groove.site_current_node.meta_author, cph_head)
            AddMetaTag("robots", Groove.site_current_node.meta_robots, cph_head)
            AddMetaTag("copyright", Groove.site_current_node.meta_copyright, cph_head)
            AddMetaTag("distribution", "Global", cph_head)

            ' resource links
            Groove.AddGenericLink(Me.Page, "edituri", CoreSettings.GetTranslatedConfigurationUrl("http://[[Boogaloo.site_root]]rsd.axd"), "application/rsd+xml", "RSD")


            

        End Sub


        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

            Dim insert_badge As Boolean = False
            ' Add the Boogaloo Badge if user signed in as Boogaloo Admin
            If CType(CoreSettings.GetSetting("ADMIN_DisplayPublicBoogalooAdminLink"), Boolean) Then
                If Context.User.IsInRole("Boogaloo Admin") Then
                    insert_badge = True
                End If
            End If

            ' Remove the generated stylesheets
            '-----------------------------------------------------------------------
            If Groove.site_current_node.theme IsNot Nothing Then


                RemoveAppThemeGeneratedHtmlLinks()

                With Groove.site_current_node.theme.manifest

                    Dim links As String = .GetHeaderHtml()

                    If Not String.IsNullOrEmpty(links) Then Page.Header.Controls.Add(New LiteralControl(links))

                End With

            End If

            Dim app_path As String = Context.Request.ApplicationPath
            If String.Equals(app_path, "/") Then app_path = String.Empty

            If insert_badge Then
                Dim badge_styles As String = Groove.GetTextFileContents(Server.MapPath("~/App_Data/CodeTemplates/boogaloobadgestyle.config"))
                badge_styles = badge_styles.Replace("[virtual_dir]", app_path)
                Groove.AddControlToHeader(Me.Page, New LiteralControl(badge_styles))
            End If


            CorrectUrlRewriteFormAction()

            ' Insert the Boogaloo Badge to patch previous problems with inserting a control
            ' into an empty form.
            '-----------------------------------------------------------------------
            If insert_badge Then

                Dim stringWriter As New System.IO.StringWriter
                Dim htmlWriter As New HtmlTextWriter(stringWriter)

                MyBase.Render(htmlWriter)

                Dim html As String = stringWriter.ToString
                
                Dim path_designer As String = String.Format("{0}{1}Designer.aspx?node={2}", app_path, Groove.path_admin_site.Replace("~", String.Empty), Groove.site_current_node.node_id.ToString)
                Dim badge_html As String = String.Format("<span id=""boogalooBadge""><a href=""{0}"" title=""Link to Boogaloo page administration"">Edit this page</a></span>", path_designer)

                html = html.Insert(html.ToLowerInvariant.LastIndexOf("</body>") - 1, badge_html)

                writer.Write(html)

            Else

                MyBase.Render(writer)

            End If

        End Sub



        Private Sub AddMetaTag(ByVal name As String, ByVal content As String, ByVal cph As ContentPlaceHolder)
            If Not String.IsNullOrEmpty(content) Then
                Dim meta As New HtmlMeta
                meta.Name = name
                meta.Content = content
                If cph IsNot Nothing Then
                    cph.Controls.Add(meta)
                Else
                    Page.Header.Controls.Add(meta)
                End If

            End If
        End Sub



        Private Sub CorrectUrlRewriteFormAction()

            Dim Context As HttpContext
            Context = HttpContext.Current

            If Context.Items("FormActionAlreadyWritten") Is Nothing Then

                Page.Form.Action = Context.Request.RawUrl

                Context.Items("FormActionAlreadyWritten") = True

            End If

        End Sub


    End Class


End Namespace
